package com.inspur.gs.sbssdl.sbwhgl.sbwhby.sbwhby.back.commoncmps;

import com.inspur.edp.bef.api.lcp.ILcpFactory;
import com.inspur.edp.bef.api.lcp.IStandardLcp;
import com.inspur.edp.bef.api.services.IBefSessionManager;
import com.inspur.edp.bef.engine.entity.AssociationInfo;
import com.inspur.edp.cef.entity.changeset.ModifyChangeDetail;
import com.inspur.edp.cef.entity.condition.EntityFilter;
import com.inspur.edp.cef.entity.condition.FilterCondition;
import com.inspur.edp.cef.entity.entity.IEntityData;
import com.inspur.edp.cef.entity.entity.IEntityDataCollection;
import com.inspur.edp.dxc.spi.components.BaseCustomValidateComponent;
import com.inspur.edp.qdp.bql.api.IBqlExecuter;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import io.iec.edp.caf.runtime.config.BqlBeanUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.inspur.edp.cef.entity.entity.IValuesContainer;

import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

public class Byjhsc extends BaseCustomValidateComponent{

    private static final Logger log = LoggerFactory.getLogger(Byjhsc.class);
    private final IBqlExecuter bqlExecuter = BqlBeanUtil.getAppCtx().getBean(IBqlExecuter.class);
    private static final String sbtz = "efd56b39-0e8d-4441-9fa1-2b019b6fd862"; //设备台账
    private static final String byjh = "48950655-b905-4cb2-b359-9ca407386764"; //保养计划
    private static final String ybfk = "84ec34b9-d139-4216-8d69-09ec8145eab1"; //一保反馈
    private static final String ebfk = "cde823e0-7159-4c28-b411-165d30abfe4c"; //二保反馈
    private static final String rhrw = "0f9b3d1d-9d73-4deb-b5b1-7cb832da39e6";

    /**
     * 构建分为五步
     * 1.获取保养配置信息
     * 2.获取润滑信息
     * 3.获取一保反馈、二保反馈信息
     * 4.将信息整合覆盖一保，二保未完成反馈的数据
     * 5.插入
     */
    public void byjhscCheck() {
        //这个集合类代表设备配置信息和润滑的总和
        List<bypzxxEntity> bypzxxEntityList = new ArrayList<>();

        SpringBeanUtils.getBean(IBefSessionManager.class).createSession();
        try {
            //保养配置
            ILcpFactory iLcpFactory = SpringBeanUtils.getBean(ILcpFactory.class);
            IStandardLcp byszlcp = iLcpFactory.createLcpByBEId(byjh);  //保养计划
            IStandardLcp sbtzlcp = iLcpFactory.createLcpByBEId(sbtz);  //设备台账

            List<IEntityData> allbypzData = byszlcp.query();
            //遍历设备保养配置取值，取到设备配置的月份信息
            for (IEntityData bypzItem : allbypzData) {
                bypzxxEntity bypzxx = new bypzxxEntity();

                //主类信息
                bypzxx.setId(bypzItem.getID());
                bypzxx.setYear((String) bypzItem.getValue("year"));
                bypzxx.setSbbh((String) bypzItem.getValue("sbbh"));
                bypzxx.setSbmc((String) bypzItem.getValue("sbmc"));
                bypzxx.setGgxh((String) bypzItem.getValue("ggxh"));
                bypzxx.setXh((String) bypzItem.getValue("xh"));
                bypzxx.setShopName((String) bypzItem.getValue("shopName"));
                bypzxx.setSbbhOld((String) bypzItem.getValue("sbbh_old"));
                bypzxx.setLbmc((String) bypzItem.getValue("lbmc"));
                bypzxx.setLbbh((String) bypzItem.getValue("lbbh"));
                bypzxx.setZtmc((String) bypzItem.getValue("ztmc"));
                bypzxx.setZtbh((String) bypzItem.getValue("ztbh"));
                bypzxx.setAbcbh((String) bypzItem.getValue("abcbh"));
                bypzxx.setAbcmc((String) bypzItem.getValue("abcmc"));
                bypzxx.setBmbh((String) bypzItem.getValue("bmbh"));
                bypzxx.setBmmc((String) bypzItem.getValue("bmmc"));

                //月份信息
                Map<Integer, String> monthMap = new HashMap<>();
                for (int i = 1; i <= 12; i++) {
                    String monthValue = (String) bypzItem.getValue("month" + i);
                    if (!monthValue.equals("0")) {
                        monthMap.put(i, monthValue);
                    }
                }
                bypzxx.setMonthData(monthMap);

                //过滤设备编号
                EntityFilter filter = new EntityFilter();
                ArrayList<FilterCondition> filterConditions = (ArrayList<FilterCondition>) FilterCondition.builder().andEqual("sbbh", bypzxx.getSbbh()).build();
                filter.addFilterConditions(filterConditions);
                List<IEntityData> tzData = sbtzlcp.query(filter);
                if (!tzData.isEmpty()) {
                    String tzid = tzData.get(0).getID();

                    //一保信息
                    IEntityDataCollection ybgl = sbtzlcp.retrieve(tzid).getData().getChilds().get("bybz");
                    List<bypzxxEntity.ybpz> ybpzList = new ArrayList<>();
                    for (IEntityData ybglItem : ybgl) {
                        bypzxxEntity.ybpz ybpz = new bypzxxEntity.ybpz();
                        ybpz.setBybw((String) ((IValuesContainer) ybglItem.getValue("bybz")).getValue("bybz_bybw"));
                        ybpz.setByxm((String) ((IValuesContainer) ybglItem.getValue("bybz")).getValue("bybz_byxm"));
                        ybpz.setGxnr((String) ((IValuesContainer) ybglItem.getValue("bybz")).getValue("bybz_gxnr"));
                        ybpz.setHgbz((String) ((IValuesContainer) ybglItem.getValue("bybz")).getValue("bybz_hgbz"));
                        ybpz.setLx("一级保养");
                        ybpzList.add(ybpz);
                    }
                    bypzxx.setYbpzList(ybpzList);
                    //二保信息
                    IEntityDataCollection ebgl = sbtzlcp.retrieve(tzid).getData().getChilds().get("ebbz");
                    List<bypzxxEntity.ebpz> ebpzList = new ArrayList<>();
                    for (IEntityData ebglItem : ebgl) {
                        bypzxxEntity.ebpz ebpz = new bypzxxEntity.ebpz();
                        ebpz.setBybw((String) ((IValuesContainer) ebglItem.getValue("ebbz")).getValue("ebbz_bybw"));
                        ebpz.setByxm((String) ((IValuesContainer) ebglItem.getValue("ebbz")).getValue("ebbz_byxm"));
                        ebpz.setGxnr((String) ((IValuesContainer) ebglItem.getValue("ebbz")).getValue("ebbz_gxnr"));
                        ebpz.setHgbz((String) ((IValuesContainer) ebglItem.getValue("ebbz")).getValue("ebbz_hgbz"));
                        ebpz.setFsff((String) ((IValuesContainer) ebglItem.getValue("ebbz")).getValue("ebbz_fsff"));
                        ebpz.setGqj((String) ((IValuesContainer) ebglItem.getValue("ebbz")).getValue("ebbz_gqj"));
                        ebpz.setDegs((String) ((IValuesContainer) ebglItem.getValue("ebbz")).getValue("ebbz_degs"));
                        ebpz.setLx("二级保养");
                        ebpzList.add(ebpz);
                    }
                    bypzxx.setEbpzList(ebpzList);
                    bypzxxEntityList.add(bypzxx);
                }
            }
            ybfkSearch(iLcpFactory, bypzxxEntityList);
            ebfkSearch(iLcpFactory, bypzxxEntityList);
            deleteNotExistData(iLcpFactory);
        } finally {
            SpringBeanUtils.getBean(IBefSessionManager.class).closeCurrentSession();
        }
    }


    /**
     * 比较一保反馈中的数据，过滤插入
     */
    public void ybfkSearch(ILcpFactory iLcpFactory, List<bypzxxEntity> bypzxxSecondList) {
        IStandardLcp ybfklcp = iLcpFactory.createLcpByBEId(ybfk);
        IStandardLcp sbtzlcp = iLcpFactory.createLcpByBEId(sbtz);
        IStandardLcp rhrwlcp = iLcpFactory.createLcpByBEId(rhrw);

        Set<String> processedSbbhSet = new HashSet<>(); // 记录已处理的设备编号，避免重复调用

        for (bypzxxEntity bypzxx : bypzxxSecondList) {
            String sbbh = bypzxx.getSbbh();

            // 跳过已处理的设备
            if (!processedSbbhSet.add(sbbh)) {
                continue;
            }
            String year = bypzxx.getYear();
            String sbmc = bypzxx.getSbmc();
            String ggxh = bypzxx.getGgxh();
            String xh = bypzxx.getXh();
            String shopName = bypzxx.getShopName();
            String sbbhOld = bypzxx.getSbbhOld();
            String lbmc = bypzxx.getLbmc();
            String lbbh = bypzxx.getLbbh();
            String ztmc = bypzxx.getZtmc();
            String ztbh = bypzxx.getZtbh();
            String abcbh = bypzxx.getAbcbh();
            String abcmc = bypzxx.getAbcmc();
            String bmbh = bypzxx.getBmbh();
            String bmmc = bypzxx.getBmmc();

            Map<Integer, String> monthData = bypzxx.getMonthData();
            for (Map.Entry<Integer, String> monthItem : monthData.entrySet()) {
                String bydj = monthItem.getValue();
                if ("1".equals(bydj)) { // 建议用 equals 而不是 ==
                    String month = String.valueOf(monthItem.getKey());

                    // 查询是否已存在一保反馈
                    EntityFilter filter = new EntityFilter();
                    List<FilterCondition> builderConditions = FilterCondition.builder()
                            .andEqual("year", bypzxx.getYear())
                            .andEqual("sbbh", sbbh)
                            .andEqual("month", month)
                            .build();
                    filter.addFilterConditions((ArrayList<FilterCondition>) builderConditions);
                    List<IEntityData> ybfkquery = ybfklcp.query(filter);

                    // 插入或覆盖逻辑（保持不变）
                    if (ybfkquery.isEmpty()) {
                        // 插入新记录
                        IEntityData data = ybfklcp.retrieveDefault();
                        ModifyChangeDetail curChange = new ModifyChangeDetail(data.getID());
                        // 设置主表字段...
                        curChange.putItem("sbbh", sbbh);
                        curChange.putItem("sbmc",sbmc);
                        curChange.putItem("ggxh",ggxh);
                        curChange.putItem("xh",xh);
                        curChange.putItem("shopName",shopName);
                        curChange.putItem("sbbh_old",sbbhOld);
                        curChange.putItem("lbmc",lbmc);
                        curChange.putItem("lbbh",lbbh);
                        curChange.putItem("ztmc",ztmc);
                        curChange.putItem("ztbh",ztbh);
                        curChange.putItem("abcbh",abcbh);
                        curChange.putItem("abcmc",abcmc);
                        curChange.putItem("bmbh",bmbh);
                        curChange.putItem("bmmc",bmmc);
                        curChange.putItem("year",year);
                        curChange.putItem("month",month);


                        // 子表插入...
                        List<bypzxxEntity.ybpz> ybpzList = bypzxx.getYbpzList();
                        for (bypzxxEntity.ybpz ybpz : ybpzList) {
                            ArrayList<String> nodeCodes = new ArrayList<>();
                            nodeCodes.add("yjbyfkmx");
                            ArrayList<String> hierachyIdList = new ArrayList<>();
                            hierachyIdList.add(data.getID());
                            IEntityData childData = ybfklcp.retrieveDefaultChild(nodeCodes, hierachyIdList);
                            ModifyChangeDetail childChange = new ModifyChangeDetail(childData.getID());
                            childChange.putItem("bybw", ybpz.getBybw());
                            childChange.putItem("byxm",ybpz.getByxm());
                            childChange.putItem("gxnr",ybpz.getGxnr());
                            childChange.putItem("hgbz",ybpz.getHgbz());
                            childChange.putItem("lx",ybpz.getLx());
                            curChange.addChildChangeSet("yjbyfkmx", childChange);
                        }
                        ybfklcp.modify(curChange);
                        ybfklcp.save();
                    } else {
                        // 覆盖未完成的反馈
                        for (IEntityData iEntityData : ybfkquery) {
                            String ybfkid = iEntityData.getID();
                            ModifyChangeDetail curChange = new ModifyChangeDetail(ybfkid);
                            IEntityDataCollection yjbyfkmx = ybfklcp.retrieve(ybfkid).getData().getChilds().get("yjbyfkmx");
                            List<String> childids = new ArrayList<>();
                            boolean allFalse = true;
                            for (IEntityData item : yjbyfkmx) {
                                childids.add(item.getID());
                                Boolean isby = (Boolean) item.getValue("isby");
                                if (Boolean.TRUE.equals(isby)) {
                                    allFalse = false;
                                    break;
                                }
                            }
                            if (allFalse) {
                                ArrayList<String> nodeCodes = new ArrayList<>();
                                nodeCodes.add("yjbyfkmx");
                                ArrayList<String> hierachyIdList = new ArrayList<>();
                                hierachyIdList.add(ybfkid);
                                ybfklcp.deleteChild(nodeCodes, hierachyIdList, childids);
                                // 重新插入新明细...
                                List<bypzxxEntity.ybpz> ybpzList = bypzxx.getYbpzList();
                                for (bypzxxEntity.ybpz ybpz : ybpzList) {
                                    IEntityData childData = ybfklcp.retrieveDefaultChild(nodeCodes, hierachyIdList);
                                    ModifyChangeDetail childChange = new ModifyChangeDetail(childData.getID());
                                    childChange.putItem("bybw", ybpz.getBybw());
                                    childChange.putItem("byxm",ybpz.getByxm());
                                    childChange.putItem("gxnr",ybpz.getGxnr());
                                    childChange.putItem("hgbz",ybpz.getHgbz());
                                    childChange.putItem("lx",ybpz.getLx());
                                    curChange.addChildChangeSet("yjbyfkmx", childChange);
                                }
                            }
                            ybfklcp.modify(curChange);
                            ybfklcp.save();
                        }
                    }
                }
            }

            // ✅ 润滑任务：每台设备只调用一次，在 month 循环外
            try {
                EntityFilter filter = new EntityFilter();
                filter.addFilterConditions((ArrayList<FilterCondition>) FilterCondition.builder().andEqual("sbbh", sbbh).build());
                List<IEntityData> tzData = sbtzlcp.query(filter);
                if (!tzData.isEmpty()) {
                    ArrayList<String> ids = new ArrayList<>();
                    ids.add(tzData.get(0).getID());
                    rhrwlcp.executeCustomAction("LuTaskCreatd", ids);
                    log.info("已为设备 {} 生成润滑任务", sbbh);
                }
            } catch (Exception e) {
                log.error("生成润滑任务失败，设备编号：{}", sbbh, e);
            }
        }
    }

    /**
     * 比较二保反馈中的数据，过滤插入
     */
    public void ebfkSearch(ILcpFactory iLcpFactory, List<bypzxxEntity> bypzxxSecondList) {
        IStandardLcp ebfklcp = iLcpFactory.createLcpByBEId(ebfk);
        IStandardLcp sbtzlcp = iLcpFactory.createLcpByBEId(sbtz);
        IStandardLcp rhrwlcp = iLcpFactory.createLcpByBEId(rhrw);

        Set<String> processedSbbhSet = new HashSet<>(); // 记录已处理的设备编号，避免重复调用

        for (bypzxxEntity bypzxx : bypzxxSecondList) {
            String sbbh = bypzxx.getSbbh();

            // 跳过已处理的设备
            if (!processedSbbhSet.add(sbbh)) {
                continue;
            }
            String year = bypzxx.getYear();
            String sbmc = bypzxx.getSbmc();
            String ggxh = bypzxx.getGgxh();
            String xh = bypzxx.getXh();
            String shopName = bypzxx.getShopName();
            String sbbhOld = bypzxx.getSbbhOld();
            String lbmc = bypzxx.getLbmc();
            String lbbh = bypzxx.getLbbh();
            String ztmc = bypzxx.getZtmc();
            String ztbh = bypzxx.getZtbh();
            String abcbh = bypzxx.getAbcbh();
            String abcmc = bypzxx.getAbcmc();
            String bmbh = bypzxx.getBmbh();
            String bmmc = bypzxx.getBmmc();

            Map<Integer, String> monthData = bypzxx.getMonthData();
            for (Map.Entry<Integer, String> monthItem : monthData.entrySet()) {
                String bydj = monthItem.getValue();
                if ("2".equals(bydj)) { // 建议用 equals 而不是 ==
                    String month = String.valueOf(monthItem.getKey());

                    // 查询是否已存在一保反馈
                    EntityFilter filter = new EntityFilter();
                    List<FilterCondition> builderConditions = FilterCondition.builder()
                            .andEqual("year", bypzxx.getYear())
                            .andEqual("sbbh", sbbh)
                            .andEqual("month", month)
                            .build();
                    filter.addFilterConditions((ArrayList<FilterCondition>) builderConditions);
                    List<IEntityData> ebfkquery = ebfklcp.query(filter);

                    // 插入或覆盖逻辑（保持不变）
                    if (ebfkquery.isEmpty()) {
                        // 插入新记录
                        IEntityData data = ebfklcp.retrieveDefault();
                        ModifyChangeDetail curChange = new ModifyChangeDetail(data.getID());
                        // 设置主表字段...
                        curChange.putItem("sbbh", sbbh);
                        curChange.putItem("sbmc",sbmc);
                        curChange.putItem("ggxh",ggxh);
                        curChange.putItem("xh",xh);
                        curChange.putItem("shopName",shopName);
                        curChange.putItem("sbbh_old",sbbhOld);
                        curChange.putItem("lbmc",lbmc);
                        curChange.putItem("lbbh",lbbh);
                        curChange.putItem("ztmc",ztmc);
                        curChange.putItem("ztbh",ztbh);
                        curChange.putItem("abcbh",abcbh);
                        curChange.putItem("abcmc",abcmc);
                        curChange.putItem("bmbh",bmbh);
                        curChange.putItem("bmmc",bmmc);
                        curChange.putItem("year",year);
                        curChange.putItem("month",month);


                        // 子表插入...
                        List<bypzxxEntity.ebpz> ebpzList = bypzxx.getEbpzList();
                        for (bypzxxEntity.ebpz ebpz : ebpzList) {
                            ArrayList<String> nodeCodes = new ArrayList<>();
                            nodeCodes.add("ejbyfkmx");
                            ArrayList<String> hierachyIdList = new ArrayList<>();
                            hierachyIdList.add(data.getID());
                            IEntityData childData = ebfklcp.retrieveDefaultChild(nodeCodes, hierachyIdList);
                            ModifyChangeDetail childChange = new ModifyChangeDetail(childData.getID());
                            childChange.putItem("bybw",ebpz.getBybw());
                            childChange.putItem("byxm",ebpz.getByxm());
                            childChange.putItem("gxnr",ebpz.getGxnr());
                            childChange.putItem("hgbz",ebpz.getHgbz());
                            childChange.putItem("lx",ebpz.getLx());
                            childChange.putItem("fsff",ebpz.getFsff());
                            childChange.putItem("gqj",ebpz.getGqj());
                            childChange.putItem("degs",ebpz.getDegs());
                            curChange.addChildChangeSet("ejbyfkmx", childChange);
                        }
                        ebfklcp.modify(curChange);
                        ebfklcp.save();
                    } else {
                        // 覆盖未完成的反馈
                        for (IEntityData iEntityData : ebfkquery) {
                            String ebfkid = iEntityData.getID();
                            ModifyChangeDetail curChange = new ModifyChangeDetail(ebfkid);
                            IEntityDataCollection ejbyfkmx = ebfklcp.retrieve(ebfkid).getData().getChilds().get("ejbyfkmx");
                            List<String> childids = new ArrayList<>();
                            boolean allFalse = true;
                            for (IEntityData item : ejbyfkmx) {
                                childids.add(item.getID());
                                Boolean isby = (Boolean) item.getValue("isby");
                                if (Boolean.TRUE.equals(isby)) {
                                    allFalse = false;
                                    break;
                                }
                            }
                            if (allFalse) {
                                ArrayList<String> nodeCodes = new ArrayList<>();
                                nodeCodes.add("ejbyfkmx");
                                ArrayList<String> hierachyIdList = new ArrayList<>();
                                hierachyIdList.add(ebfkid);
                                ebfklcp.deleteChild(nodeCodes, hierachyIdList, childids);
                                // 重新插入新明细...
                                List<bypzxxEntity.ebpz> ebpzList = bypzxx.getEbpzList();
                                for (bypzxxEntity.ebpz ebpz : ebpzList) {
                                    IEntityData childData = ebfklcp.retrieveDefaultChild(nodeCodes, hierachyIdList);
                                    ModifyChangeDetail childChange = new ModifyChangeDetail(childData.getID());
                                    childChange.putItem("bybw",ebpz.getBybw());
                                    childChange.putItem("byxm",ebpz.getByxm());
                                    childChange.putItem("gxnr",ebpz.getGxnr());
                                    childChange.putItem("hgbz",ebpz.getHgbz());
                                    childChange.putItem("lx",ebpz.getLx());
                                    childChange.putItem("fsff",ebpz.getFsff());
                                    childChange.putItem("gqj",ebpz.getGqj());
                                    childChange.putItem("degs",ebpz.getDegs());
                                    curChange.addChildChangeSet("ejbyfkmx", childChange);
                                }
                            }
                            ebfklcp.modify(curChange);
                            ebfklcp.save();
                        }
                    }
                }
            }

            // ✅ 润滑任务：每台设备只调用一次，在 month 循环外
            try {
                EntityFilter filter = new EntityFilter();
                filter.addFilterConditions((ArrayList<FilterCondition>) FilterCondition.builder().andEqual("sbbh", sbbh).build());
                List<IEntityData> tzData = sbtzlcp.query(filter);
                if (!tzData.isEmpty()) {
                    ArrayList<String> ids = new ArrayList<>();
                    ids.add(tzData.get(0).getID());
                    rhrwlcp.executeCustomAction("LuTaskCreatd", ids);
                    log.info("已为设备 {} 生成润滑任务", sbbh);
                }
            } catch (Exception e) {
                log.error("生成润滑任务失败，设备编号：{}", sbbh, e);
            }
        }
    }

    public void deleteNotExistData(ILcpFactory iLcpFactory){
        IStandardLcp ybfklcp = iLcpFactory.createLcpByBEId(ybfk);
        IStandardLcp ebfklcp = iLcpFactory.createLcpByBEId(ebfk);
        //清除未来不存在的保养任务
        int year = LocalDate.now().getYear()+1;
        String yearStr = String.valueOf(year);
        EntityFilter filter = new EntityFilter();
        List<FilterCondition> builderConditions = FilterCondition.builder()
                .andGreater("year",yearStr)
                .build();
        filter.addFilterConditions((ArrayList<FilterCondition>) builderConditions);

        //删除一保不存在数据
        List<IEntityData> ybNotExistData = ybfklcp.query(filter);
        List<String> ybNotIds = ybNotExistData.stream().map(s -> s.getID()).collect(Collectors.toList());
        ybfklcp.delete(ybNotIds);
        ybfklcp.save();

        //删除二保不存在数据
        List<IEntityData> ebNotExistData = ebfklcp.query(filter);
        List<String> ebNotIds = ebNotExistData.stream().map(s -> s.getID()).collect(Collectors.toList());
        ebfklcp.delete(ebNotIds);
        ebfklcp.save();

    }

}